<template>
  <div class="flex items-center justify-center px-2.5 md:px-6 bg-[#fff]">
    <div class="w-full max-w-xl text-center mt-4 mb-12">
      <!-- 文字 -->
      <div class="mb-14">
        <div class="mb-10 block text-xl font-bold">
          {{ i18nStore.translate('OK_yunpan') }}
        </div>
        <div class="mb-0.5 text-3xl font-extrabold md:text-4xl">
          {{ i18nStore.translate('create_new_account') }}
        </div>
        <div class="text-xl font-normal md:text-2xl">
          {{
            i18nStore.translate(
              'please_fill_in_the_information_to_create_an_account'
            )
          }}
        </div>
      </div>
      <!-- 表单 -->
      <div>
        <div class="mb-3">
          <div class="md:flex justify-center items-center mb-2">
            <div class="w-[100px] font-bold mr-4 md:text-right text-left mb-1">
              {{ i18nStore.translate('account') }}
            </div>
            <input
              type="text"
              v-model="emailAndPhone"
              v-bind="emailAndPhoneAttrs"
              :placeholder="i18nStore.translate('please_enter_email_or_phone')"
              class="md:w-[330px] w-[100%] px-5 py-2.5 font-bold rounded-lg border-0 focus:outline-theme-color text-lg bg-[#f4f5f6]"
            />
          </div>
          <div class="flex md:pl-[180px] text-xs text-red-600">
            {{ errors.emailAndPhone }}
          </div>
        </div>
        <div class="mb-3">
          <div class="md:flex justify-center items-center mb-2">
            <div class="w-[100px] font-bold mr-4 md:text-right text-left mb-1">
              {{ i18nStore.translate('verification_code') }}
            </div>
            <div class="relative">
              <input
                type="text"
                v-model="code"
                v-bind="codeAttrs"
                class="md:w-[330px] w-[100%] px-5 py-2.5 font-bold rounded-lg border-0 focus:outline-theme-color text-lg bg-[#f4f5f6]"
              />
              <!-- placeholder="请输入验证码" -->
              <div
                class="absolute right-5 top-[50%] translate-y-[-50%] font-bold text-theme-color cursor-pointer"
                v-if="conutDown"
              >
                {{ i18nStore.translate('resend') + conutDown + 's' }}
              </div>
              <div
                class="absolute right-5 top-[50%] translate-y-[-50%] font-bold text-theme-color cursor-pointer"
                v-else
                @click="getCode"
              >
                {{ i18nStore.translate('get_verification_code') }}
              </div>
            </div>
          </div>
          <div
            class="flex md:pl-[180px] text-xs text-red-600"
            v-if="isCodeError"
          >
            {{ i18nStore.translate('verification_code_error') }}
          </div>
        </div>
        <div class="mb-3">
          <div class="md:flex justify-center items-center mb-2">
            <div class="w-[100px] font-bold mr-4 md:text-right text-left mb-1">
              {{ i18nStore.translate('Nickname') }}
            </div>
            <input
              type="text"
              v-model="nickname"
              v-bind="nicknameAttrs"
              :placeholder="i18nStore.translate('please_enter_a_nickname')"
              class="md:w-[330px] w-[100%] px-5 py-2.5 font-bold rounded-lg border-0 focus:outline-theme-color text-lg bg-[#f4f5f6]"
            />
          </div>
          <div class="flex md:pl-[180px] text-xs text-red-600">
            {{ errors.nickname }}
          </div>
        </div>
        <div class="mb-3">
          <div class="md:flex justify-center items-center mb-2">
            <div class="w-[100px] font-bold mr-4 md:text-right text-left mb-1">
              {{ i18nStore.translate('create_password') }}
            </div>
            <input
              type="password"
              v-model="password"
              v-bind="passwordAttrs"
              :placeholder="i18nStore.translate('please_enter_password')"
              class="md:w-[330px] w-[100%] px-5 py-2.5 font-bold rounded-lg border-0 focus:outline-theme-color text-lg bg-[#f4f5f6]"
            />
          </div>
          <div class="flex md:pl-[180px] text-xs text-red-600">
            {{ errors.password }}
          </div>
        </div>
        <div class="mb-3">
          <div class="md:flex justify-center items-center mb-2">
            <div class="w-[100px] font-bold mr-4 md:text-right text-left mb-1">
              {{ i18nStore.translate('confirm_password') }}
            </div>
            <input
              type="password"
              v-model="confirmPassword"
              v-bind="confirmPasswordAttrs"
              :placeholder="i18nStore.translate('please_enter_password_again')"
              class="md:w-[330px] w-[100%] px-5 py-2.5 font-bold rounded-lg border-0 focus:outline-theme-color text-lg bg-[#f4f5f6]"
            />
          </div>
          <div class="flex md:pl-[180px] text-xs text-red-600">
            {{ errors.confirmPassword }}
          </div>
        </div>
        <!-- tips -->
        <div class="flex justify-center items-center mb-6">
          <div
            class="w-[200px] flex justify-center items-center rounded-lg border-2 border-black px-3.5 py-1.5 cursor-pointer"
            @click="register"
          >
            <div class="mr-1 text-lg font-extrabold">
              {{ i18nStore.translate('sign_up_account') }}
            </div>
            <svg
              data-v-0249f6ea=""
              xmlns="http://www.w3.org/2000/svg"
              width="20px"
              height="20px"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              class="vue-feather text-theme-color -mr-1 feather feather-chevron-right"
            >
              <polyline data-v-0249f6ea="" points="9 18 15 12 9 6"></polyline>
            </svg>
          </div>
        </div>
        <div>
          <span>{{ i18nStore.translate('already_have_an_account') }}</span>
          <span class="font-bold text-theme-color cursor-pointer">
            <router-link to="/login">{{
              i18nStore.translate('sign_in_now')
            }}</router-link></span
          >
        </div>
      </div>
    </div>
    <!-- toast -->
    <Toast position="center" group="registerSuccess" />
  </div>
</template>
<script setup>
import { useRouter } from 'vue-router';
import Toast from 'primevue/toast';
import { useForm } from 'vee-validate';
import { useToast } from 'primevue/usetoast';
import { registerApi, getEmailCodeApi, getSmsCodeApi } from '@/apis/user';
import { useI18nStore } from '@/stores';
const router = useRouter();
const toast = useToast();
const i18nStore = useI18nStore();
// 表单校验
const isEmail = computed(() => {
  return emailReg(emailAndPhone.value);
});
// 校验规则
const emailReg = (value) => {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
};
const phoneReg = (value) => {
  return /^1[3-9]\d{9}$/.test(value);
};
const isCodeError = ref(false); // 验证码错误
// 表单生成器
const { values, errors, defineField, meta } = useForm({
  validationSchema: {
    emailAndPhone: (val) =>
      emailReg(val) || phoneReg(val)
        ? true
        : i18nStore.translate('please_enter_a_valid_email_or_phone_number'),
    nickname: (val) => true,
    password: (val) => true,
    confirmPassword: (val) =>
      password.value === confirmPassword.value
        ? true
        : i18nStore.translate('password_not_match'),
    code: (val) => true
  }
});
// 表单字段
const [emailAndPhone, emailAndPhoneAttrs] = defineField('emailAndPhone');
const [nickname, nicknameAttrs] = defineField('nickname');
const [password, passwordAttrs] = defineField('password');
const [confirmPassword, confirmPasswordAttrs] = defineField('confirmPassword');
const [code, codeAttrs] = defineField('code');
// 获取验证码
const conutDown = ref(0); // 验证码倒计时
const getCode = async () => {
  if (emailReg(emailAndPhone.value)) {
    const res = await getEmailCodeApi({ email: emailAndPhone.value });
    console.log(res, 'passed');
  } else if (phoneReg(emailAndPhone.value)) {
    const res = await getSmsCodeApi({ phone: emailAndPhone.value });
    console.log(res, 'passed');
  } else {
    return;
  }
  conutDown.value = 60;
  const timer = setInterval(() => {
    conutDown.value--;
    if (conutDown.value === 0) {
      clearInterval(timer);
    }
  }, 1000);
};
// 注册
const register = async () => {
  if (!meta.value.valid) {
    console.log('formInvalid');
    return;
  }
  let res;
  const formData = new FormData();
  formData.append('nickname', nickname.value);
  formData.append('password', password.value);
  formData.append('code', code.value);
  if (isEmail.value) {
    formData.append('email', emailAndPhone.value);
    formData.append('type', 1);
    res = await registerApi(formData);
    console.log(res, 'res');
  } else {
    formData.append('phone', emailAndPhone.value);
    formData.append('type', 2);
    res = await registerApi(formData);
    console.log(res, 'res');
  }
  if (res.status === -1) {
    isCodeError.value = true;
    return;
  } else if (res.status === 0) {
    toast.add({
      severity: 'success',
      summary: i18nStore.translate('sign_up_success'),
      detail: '',
      group: 'registerSuccess',
      life: 3000
    });
    setTimeout(() => {
      router.push('/login');
    }, 1500);
  }
};
</script>
<style lang="scss" scoped></style>
